package com.test.lock;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;


public class CyclicBarrierDemo {

	public static final class Soldier implements Runnable{
		private String soldier;
		private final CyclicBarrier cyclicBarrier;
		public Soldier(CyclicBarrier cyclicBarrier,String soldierName) {
			this.cyclicBarrier=cyclicBarrier;
			this.soldier = soldierName;
		}
		public void run() {
			
			//等待所有的士兵都到齐
			try {
				cyclicBarrier.await();
				doWork();
				//等待所有士兵完成工作
				cyclicBarrier.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
			
			
		}
		private void doWork() {
			try {
				Thread.sleep(Math.abs(new Random().nextInt()%10000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(soldier+":任务完成");
			
		}
	
	}
	
	public static class BarrierRun implements Runnable{
		boolean flag;
		int N;
		
		public BarrierRun(boolean flag, int n) {
			super();
			this.flag = flag;
			N = n;
		}

		public void run() {
			if (flag) {
				System.out.println("司令：[士兵"+N+"个,任务完成!]");
			}else {
				System.out.println("司令：[士兵"+N+"个,集结完毕!]");
				flag = true;
			}
			
		}
	}
	public static void main(String[] args) {
		final int N = 10;
		Thread[] allSoldier = new Thread[10];
		boolean flag = false;
		CyclicBarrier cBarrier = new CyclicBarrier(N, new BarrierRun(flag, N));
		//设置屏障点，只要是为了实现这个方法
		System.out.println("队伍集结！");
		for (int i = 0; i < 10; i++) {
			System.out.println("士兵"+i+"报道！");
			allSoldier[i] = new Thread(new Soldier(cBarrier, "士兵-"+i));
			allSoldier[i].start();
//			if (i==5) {
//				allSoldier[0].interrupt();
//			}
		}
	}
}
